package com.photologics.main;

import java.io.File;
import java.io.IOException;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.drawable.AnimationDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Toast;

import com.photologics.logic.LogicHelper;
import com.photologics.logic.SelectLevelActivity;

public class MainActivity extends Activity implements OnClickListener {
	final static String TAG = "MainActivity";
	private ImageButton startButton, helpButton, makeButton, shopButton,
			bgmButton;
	private ImageView aniGom;
	private AnimationDrawable mAni;

	private String kakao_LogicName;
	private String reduce_KakaoLogicData;
	private static final int PICK_FROM_CAMERA = 1;
	private static final int CROP_END = 2;
	private static String dirPath;
	private Uri ImageCaptureUri;

	private enum PrefsKey {
		FIRST, MUTE
	}

	@SuppressLint("SdCardPath")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.activity_main);

		IntentFilter offfilter = new IntentFilter(Intent.ACTION_SCREEN_OFF);
		registerReceiver(screenoff, offfilter);

		LogicHelper.db = new DbAdapter(this);
		LogicHelper.db.open();

		if (LogicHelper.db.getTableCount() == 0)
			LogicHelper.db.setItem();

		LogicHelper.accountInfo = new AccountInfo();

		if (!getPreferences(PrefsKey.FIRST).equals("false")) {

			HelpDialog helpDialog = new HelpDialog(this, "first");
			helpDialog.show();

			savePreferences(PrefsKey.FIRST, false);
		}

		reciveKakaoMessage();
		
		initButton();

		initBgm();

		aniGom = (ImageView) findViewById(R.id.ani_gom);
		mAni = (AnimationDrawable) aniGom.getBackground();
		mAni.start();

		initStorage();

	}

	@SuppressLint("SdCardPath")
	private void initStorage() {
		String str = Environment.getExternalStorageState();
		if (str.equals(Environment.MEDIA_MOUNTED)) {
			Log.i("폴더", "생성");
			dirPath = "/sdcard/android/data/photo_logic";
			File file = new File(dirPath);
			if (!file.exists()) // 원하는 경로에 폴더가 있는지 확인
				file.mkdirs();
		} else
			Toast.makeText(MainActivity.this, "SD Card 인식 실패",
					Toast.LENGTH_SHORT).show();
	}

	private void initBgm() {
		if (getPreferences(PrefsKey.MUTE).equals("true")) {
			bgmButton.setImageResource(R.drawable.muted_speaker);
			LogicHelper.bgmMute=true;
		} else 
			LogicHelper.bgmMute=false;
		
		if (LogicHelper.backgroundMusic == null)
			LogicHelper.backgroundMusic = new BackgroundMusic(this);
		LogicHelper.backgroundMusic.onStart();
	}

	private void reciveKakaoMessage() {
		String kakaoMessage = null;
		Intent intent = getIntent();
		if (intent.getData() != null) {
			kakaoMessage = intent.getData().toString();
			kakao_LogicName = kakaoMessage.split("//")[1];
			reduce_KakaoLogicData = kakaoMessage.split("//")[2];

			Intent mintent = new Intent(MainActivity.this,
					SelectLogicActivity.class);
			mintent.putExtra("kakaoName", kakao_LogicName);
			mintent.putExtra("kakaoData", reduce_KakaoLogicData);
			mintent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(mintent);
		}
	}

	private void initButton() {
		startButton = (ImageButton) findViewById(R.id.button_start);
		helpButton = (ImageButton) findViewById(R.id.button_help);
		makeButton = (ImageButton) findViewById(R.id.button_makelogic);
		shopButton = (ImageButton) findViewById(R.id.button_shop);
		bgmButton = (ImageButton) findViewById(R.id.button_bgm);

		startButton.setOnClickListener(this);
		helpButton.setOnClickListener(this);
		makeButton.setOnClickListener(this);
		shopButton.setOnClickListener(this);
		bgmButton.setOnClickListener(this);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

	@SuppressWarnings("deprecation")
	@Override
	public void onClick(View v) {
		if (v.getId() == R.id.button_start) {

			Intent intent = new Intent(MainActivity.this,
					SelectLogicActivity.class);
			startActivity(intent);
		} else if (v.getId() == R.id.button_makelogic) {
			showDialog(1);
		} else if (v.getId() == R.id.button_shop) {
			ShopDialog shopdialog = new ShopDialog(this);
			shopdialog.show();
		} else if (v.getId() == R.id.button_help) {
			HelpDialog helpDialog = new HelpDialog(this, "click");
			helpDialog.show();
		} else if (v.getId() == R.id.button_bgm) {
			if (getPreferences(PrefsKey.MUTE).equals("true")) {
				savePreferences(PrefsKey.MUTE, false);
				LogicHelper.bgmMute=false;
				bgmButton.setImageResource(R.drawable.speaker);
				LogicHelper.backgroundMusic.onStart();
			} else {
				savePreferences(PrefsKey.MUTE, true);
				LogicHelper.bgmMute=true;
				bgmButton.setImageResource(R.drawable.muted_speaker);
				LogicHelper.backgroundMusic.onPause();
			}
		}
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case 1:
			final Dialog makeLogicDialog = new Dialog(this, R.style.DialogTheme);
			View view1 = getLayoutInflater().inflate(R.layout.makelogic_dialog,
					null);
			makeLogicDialog.setContentView(view1);
			makeLogicDialog.setCanceledOnTouchOutside(true);
			Button make;
			Button bring;
			make = (Button) view1.findViewById(R.id.dialog_make);
			make.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					Intent cameraIntent = new Intent(
							MediaStore.ACTION_IMAGE_CAPTURE);

					String fileName = System.currentTimeMillis() + ".jpg";
					ImageCaptureUri = Uri.fromFile(new File(Environment
							.getExternalStorageDirectory(), fileName));

					cameraIntent.putExtra(
							android.provider.MediaStore.EXTRA_OUTPUT,
							ImageCaptureUri);
					startActivityForResult(cameraIntent, PICK_FROM_CAMERA);

				}
			});

			bring = (Button) view1.findViewById(R.id.dialog_bring);
			bring.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					Log.i("앨범에서가져오기", "ok");
					Intent albumIntent = new Intent(
							Intent.ACTION_GET_CONTENT,
							android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
					albumIntent.setType("image/*");
					albumIntent.putExtra("crop", "true");
					albumIntent.putExtra("aspectX", 1);
					albumIntent.putExtra("aspectY", 1);
					albumIntent.putExtra(MediaStore.EXTRA_OUTPUT, getTempUri());
					albumIntent.putExtra("outputFormat", // 포맷방식
							Bitmap.CompressFormat.JPEG.toString());
					startActivityForResult(albumIntent, CROP_END);

				}
			});
			return makeLogicDialog;
		case 2:
			final Dialog existDialog = new Dialog(this, R.style.DialogTheme);
			View view2 = getLayoutInflater()
					.inflate(R.layout.existdialog, null);
			existDialog.setContentView(view2);
			existDialog.setCanceledOnTouchOutside(true);
			ImageButton ok;
			ImageButton cancle;

			ok = (ImageButton) view2.findViewById(R.id.button_ok);
			ok.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					LogicHelper.backgroundMusic.onPause();
					finish();
				}
			});

			cancle = (ImageButton) view2.findViewById(R.id.button_cancel);
			cancle.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					existDialog.cancel();
				}
			});
			return existDialog;
		}
		return null;

	}

	private Uri getTempUri() {
		return Uri.fromFile(getTempFile());
	}

	private File getTempFile() {

		if (isSDCARDMOUNTED()) {
			File f = new File(dirPath, "Temp.jpg");
			try {
				f.createNewFile(); // 외장메모리에 temp.jpg 파일 생성
				Log.i("사진생성", "ok");
			} catch (IOException e) {
			}

			return f;
		} else
			return null;
	}

	private boolean isSDCARDMOUNTED() {
		String status = Environment.getExternalStorageState();
		if (status.equals(Environment.MEDIA_MOUNTED))
			return true;

		return false;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode != RESULT_OK) {
			return;
		}
		switch (requestCode) {
		case PICK_FROM_CAMERA:
			Intent intent = new Intent("com.android.camera.action.CROP");
			intent.setDataAndType(ImageCaptureUri, "image/*");

			intent.putExtra("crop", "true");
			intent.putExtra("aspectX", 1);
			intent.putExtra("aspectY", 1);

			intent.putExtra(MediaStore.EXTRA_OUTPUT, getTempUri());
			intent.putExtra("outputFormat", // 포맷방식
					Bitmap.CompressFormat.JPEG.toString());
			startActivityForResult(intent, CROP_END);

			break;

		case CROP_END:

			Intent hintent = new Intent(MainActivity.this,
					SelectLevelActivity.class);
			hintent.putExtra("filepath", dirPath + "/temp.jpg");
			startActivity(hintent);

		}

	}

	private String getPreferences(PrefsKey key) {
		SharedPreferences pref = getSharedPreferences("pref", MODE_PRIVATE);
		return pref.getString(key.name(), "");
	}

	private void savePreferences(PrefsKey key, Boolean bool) {
		SharedPreferences pref = getSharedPreferences("pref", MODE_PRIVATE);
		SharedPreferences.Editor editor = pref.edit();
		editor.putString(key.name(), bool.toString());
		editor.commit();
	}

	@SuppressWarnings("deprecation")
	@Override
	public void onBackPressed() {
		showDialog(2);
	}

	protected void onPause() {
		LogicHelper.backgroundMusic.onPause(getApplicationContext());
		super.onPause();
	}

	public void onDestroy() {
		super.onDestroy();
		unregisterReceiver(screenoff);
	}

	BroadcastReceiver screenoff = new BroadcastReceiver() {
		public static final String Screenoff = "android.intent.action.SCREEN_OFF";

		@Override
		public void onReceive(Context context, Intent intent) {
			if (!intent.getAction().equals(Screenoff))
				return;
			LogicHelper.backgroundMusic.onPause(getApplicationContext());
		}
	};

	@Override
	protected void onResume() {
		if (!getPreferences(PrefsKey.MUTE).equals("true")) {
			LogicHelper.backgroundMusic.onStart();
		}
		super.onResume();
	}
}
